package com.lagou.edu.controller;

import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.EmailServiceFeignClient;
import com.lagou.edu.service.LagouCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Tao Zheng
 * @classNmae: LagouCodeController
 * @packageName: com.lagou.edu.controller
 * @description:
 * @DATE: 2021/9/8 16:46
 */
@RestController
@RequestMapping("/api/code")
public class LagouCodeController {

    @Autowired
    private LagouCodeService codeService;

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    /**
     * 生成随机验证码，并保存到code表中，再发送邮件
     * @param email
     * @return
     */
    @GetMapping(value = "/generateCode/{email}")
    public boolean generateCode(@PathVariable("email") String email){
        if (!StringUtils.isEmpty(email)){
            String code = getRandomCode();
            codeService.createAuthCode(email, code);
            //  todo 调用邮件服务
            return emailServiceFeignClient.sendEmail(email,code);

        }
        return false;
    }

    /**
     * 校验验证码
     * @param email
     * @param code
     * @return
     */
    @GetMapping(value = "/validateCode/{email}/{code}")
    public int validateCode(@PathVariable("email") String email, @PathVariable("code") String code){
        //1:正确，2:错误，0:超时
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(code) ){
            return 2;
        } else {
            return codeService.validateCode(email, code);
        }
    }

    /**
     * 生成六位随机数
     * @return
     */
    private String getRandomCode() {

        StringBuffer codeBuffer = new StringBuffer();

        for (int i = 0; i < 6; i++) {
            double s = Math.random();
            codeBuffer.append((int)(s*10));
        }
        return codeBuffer.toString();
    }
}
